const { request }  = require('../../request/index.js');
const crypto = require("../../utils/test");
const ImageSource=require("../../utils/image_path")
const dataGet=require("../../request/dataGet.js")
const app = getApp();
Page({
    //页面的初始数据
    data: {
        NavbarHeight:app.globalData.navBarHeight + app.globalData.statusBarHeight,
        WindowWidth:app.globalData.windowWidth,
        navigationSetting:{
            title:'收藏板',
            model:0,
        },
        CMIndex:0,
        CardNum:0,
        MedalNum:0,
        PageIndex:0,
        unknownCardSrc:"",
        blankCard:"",
        cardsCategory:["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"],
        cardsData:[],
        detailData:[],
        componentIndex:"",
        medalData:[],
        coupleActive:[],
        medalTitle:["生椰拿铁达人","美式最经典","拿铁达人","春暖花开","抹茶控","摩卡爱好者",],
        coupleShowIsActive:0,
        showIndex:0,
        showDate:"",
        numLight:4,
    },
    //加载
    onLoad(){
        this.downloadMedalImage();
        const nullCardData=wx.getStorageSync("nullCardData");
        this.setData({
            unknownCardSrc:nullCardData.data[0],
            blankCard:nullCardData.data[1]
        });
    },
    //在次进入
    async onShow(){
        if(app.globalData.userCardChangeFlag==1){
            console.log("改变")
            await dataGet.getUserCardData();
            app.globalData.userCardChangeFlag=0;
        }
        const data=wx.getStorageSync("userCards");
        this.setData({
            cardsData:data.data,
        });
        this.getAllNum();
        if(app.globalData.skipPage==1){
            this.setData({
                PageIndex:0,
                CMIndex:0
            })
            app.globalData.skipPage=0
        }
    },
    //获取全部数字信息
    getAllNum(){
        var medalCount=0,cardCount=0
        for(let i=0; i<this.data.cardsData.length;i++){
            if(this.data.cardsData[i].length>=this.data.numLight){
                medalCount++;
            }
            cardCount+=this.data.cardsData[i].length
        }
        var userCouples=wx.getStorageSync("userCouples");
        var list=[]
        userCouples.data.forEach(item=>{
           list.push(parseInt(item.message[0]))
        })
        list=Array.from(new Set(list))
        var coupleList=[]
        for(var i=0; i<6; i++){
            if(list.indexOf(i)!=-1){
                coupleList.push(1)
            }else {
                coupleList.push(0)
            }
        }
        console.log(coupleList)
        this.setData({
            CardNum:cardCount,
            MedalNum:medalCount,
            coupleActive:coupleList,
        })
    },
    //下载勋章
    downloadMedalImage(){
        var that = this;
        var fileList=[];
        for(let i=0;i<ImageSource.imageList[1].length;i++){
            fileList.push(ImageSource.Base+ImageSource.page[1]+ImageSource.imageList[1][i])
        }
        wx.cloud.getTempFileURL({
            fileList:fileList,
            success:(res)=>{
                console.log(res)
                var list=[];
                for(let i=0;i<res.fileList.length;i++){
                    list.push(res.fileList[i].tempFileURL)
                }
                that.setData({
                    medalData:list
                })
                console.log(this.data.medalData)
            }
        })
    },
    //获取卡片数据
    getCardsData(){
        var that=this;
        setTimeout(()=>{
            let params={
                url:'/userCard',
                method: 'GET',
                data: {
                    openId:app.globalData.openId,
                },
            }
            request(params).then(res=>{
                const data=JSON.parse(crypto.AES_DE(res.data))
                let category = []
                let values=[];
                let categoryAll=["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"]
                var temp=Object.values(data)
                var fileList=new Array();
                console.log(temp)
                for (let i = 0; i < Object.keys(data).length; i++){
                    for(let j=0;j<temp[i].length;j++){
                        fileList.push(ImageSource.Base+"/icon/roleCard/"+temp[i][j].imageSrc);
                    }
                }
                console.log(fileList)
                new Promise(resolve =>{
                    wx.cloud.getTempFileURL({
                        fileList:fileList,
                        success:res=>{
                            console.log(res);
                            var count=0;
                            for (let i = 0; i < Object.keys(data).length; i++){
                                for(let j=0;j<temp[i].length;j++){
                                    temp[i][j].imageSrc=res.fileList[count++].tempFileURL;
                                }
                            }
                            that.setData({
                                CardNum:count,
                            })
                            for (let i = 0; i < Object.keys(data).length; i++){
                                category.push(Object.keys(data)[i]);
                            }
                            categoryAll.forEach(tmp=>{
                                let index=category.indexOf(tmp);
                                console.log(tmp+index)
                                if(index==-1){
                                    values.push([])
                                }
                                else{
                                    values.push(temp[index]);
                                }
                            })
                            console.log(values);
                            var medalCount=0;
                            for(let i=0; i<values.length; i++){
                                if(values[i].length>=that.data.numLight)
                                    medalCount++;
                            }
                            that.setData({
                                MedalNum:medalCount,
                            })
                            resolve();
                        }
                    })
                }).then(()=>{
                    that.setData({
                        cardsCategory:categoryAll,
                        cardsData:values,
                    })
                    wx.setStorageSync("userCards",{time:Date.now(),data:that.data.cardsData});
                    console.log(that.data.cardsData)
                })
            })
        },800)
    },
    //点击事件
    CMIndexItemTap(e){
        var that = this;
        const {index}=e.currentTarget.dataset;
        if(index==1&&this.data.CMIndex==0) this.setScrollDistance();
        setTimeout(()=>{
            this.setData({
                CMIndex:index
            })
            },100
        )
        if(index==0&&this.data.CMIndex==1){
            var distance=parseFloat(wx.getStorageSync("collectionCardDistance"));
            setTimeout(()=>{
                wx.pageScrollTo({
                    scrollTop:distance,
                    duration:0
                })
                },100
            )

        }
    },
    //卡片详情跳转
    CardDetailsItemTap(e){
        this.setScrollDistance();
        const index=e.currentTarget.dataset.index;
        if(this.data.cardsData[parseInt(index)].length==0){return}
        this.setData({
            componentIndex:index,
        })
        var that=this;
        setTimeout(()=>{
                this.setData({
                    navigationSetting:{
                        title:this.data.cardsCategory[parseInt(index)],
                        model:1,},
                    detailData:this.data.cardsData[parseInt(index)],
                    PageIndex:1,
                });
                console.log(this.data.detailData)
            },100
        )
    },
    //返回
    returnPage(e){
        setTimeout(()=> {
            this.setData({
                PageIndex: e.detail.PageIndex,
                navigationSetting: {
                    title: '收藏板',
                    model: 0,
                },
            })
        },100);
        this.onShow();
        // var child = this.selectComponent('.childComponent');
        // var r=child.returnData()
        // console.log(r);
        // let l="cardsData["+ this.data.componentIndex+"]";
        // this.setData({
        //     [l]:r,
        // })
        //wx.setStorageSync("userData",{time:Date.now(),data:this.data.cardsData});
        var distance=parseFloat(wx.getStorageSync("collectionCardDistance"));
        setTimeout(()=>{
                wx.pageScrollTo({
                    scrollTop:distance,
                    duration:0
                })
            },100
        )
    },
    //获取滚动位置
    setScrollDistance(){
        var query1 = wx.createSelectorQuery();
        query1.select('.btn_line').boundingClientRect()
        query1.exec((res)=> {
            var distance_tmp=res[0].bottom;
            var query2 = wx.createSelectorQuery();
            //选择id
            query2.select('.collectionCard').boundingClientRect()
            query2.exec((resc)=> {
                //res就是 所有标签为mjltest的元素的信息 的数组
                var distance=parseFloat(distance_tmp)-32-parseFloat(resc[0].top);
                wx.setStorageSync("collectionCardDistance", distance);
            })
        })
    },
    //获取优惠券
    getCouples(){
        var that = this;
        var list=[];
        var id=that.data.showIndex
        var days=7
        list.push(id)
        list.push(app.globalData.openId)
        list.push(app.globalData.nowTime)
        list.push("unused")
        var message=list.join('@')
        let params={
            url:'/makeCouple',
            method: 'POST',
            header: {
                "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
            },
            data: {
                message:crypto.AES_EN(message),
            },
        }
        request(params).then(()=>{
            dataGet.getCouples()
            let l="coupleActive["+that.data.showIndex+"]"
            that.setData({
                [l]:1,
            })
            that.closeShowCouple();
        })
    },
    //优惠券点击事件
    getCoupleItemTap(e){
        console.log(e.currentTarget.dataset.index)
        const index=e.currentTarget.dataset.index
        var nowTime=new Date(app.globalData.nowTime.substring(0,10))
        console.log(nowTime)
        let date=new Date();
        date.setDate(nowTime.getDate() + 7)
        date=date.toISOString().substring(0,10)
        this.setData({
            coupleShowIsActive:1,
            showIndex:index,
            showDate:date
        })
        //this.getCouples(index)
    },
    //关闭优惠券弹窗
    closeShowCouple(){
        this.setData({
            coupleShowIsActive:0,
        })
    },
    //使用优惠券
    useCouple(){
        var that = this;
        var list=[];
        var id=that.data.showIndex
        var days=7
        list.push(id)
        list.push(app.globalData.openId)
        list.push(app.globalData.nowTime)
        list.push("used")
        var message=list.join('@')
        let params={
            url:'/makeCouple',
            method: 'POST',
            header: {
                "Content-Type": "application/x-www-form-urlencoded" //POST方式是这个
            },
            data: {
                message:crypto.AES_EN(message),
            },
        }
        request(params).then(()=>{
            dataGet.getCouples()
            let l="coupleActive["+that.data.showIndex+"]"
            that.setData({
                [l]:1,
            })
            wx.showModal({
                title:"您花4.8折喝了一杯非常好喝的"+that.data.cardsCategory[that.data.showIndex],
                duration:1500
            })
            that.closeShowCouple();
        })
    },
})